const socket = new WebSocket("ws://localhost:8082");
socket.addEventListener("open", function (event) {
    socket.send(JSON.stringify({
        type: "FULL_DATA"
    }));
});

socket.addEventListener("message", function (event) {
    let data = JSON.parse(event.data)
    if (data.type == "megadice_data") {
        queueUpdate(data.data);
    }
    if (data.type == "goal_tips") {
        goalTips(data.data);
    }
});

socket.addEventListener("close", function (event) {
})


let pendingUpdates = new Map();

function queueUpdate(data) {
    for (let i = 0; i < data.length; i++) {
        let match = data[i]
        pendingUpdates.set(match.id, match);
    }
}

function applyUpdates() {
    pendingUpdates.forEach((match, matchId) => {
        updateMatch(matchId, match);
    });
    pendingUpdates.clear();
    requestAnimationFrame(applyUpdates);
}

requestAnimationFrame(applyUpdates);


function updateMatch(matchId, match) {
    const matchElement = document.getElementById(`${matchId}`);
    const container = document.getElementById("match-list");
    if (!matchElement) {
        // 创建比赛
        let el = createMatch(match)
        container.appendChild(el)
        return
    } else {
        if (match.time) {
            document.getElementById(`${match.id}_time`).textContent = match.time
        }
        if (match.score) {
            document.getElementById(`${match.id}_score`).textContent = match.score
        }
        if (match.handap && match.handap.length > 0) {
            let handapEl = match.handap?.slice(0, 3).map(h => {
                return `
                    <div class="handicap-row">
                       <span>${h.v}</span>
                       <span class="odds-cell">
                           <span class="odds-item">${h.a}</span> 
                       </span>
                       <span class="odds-cell">
                           <span class="odds-item">${h.b}</span>  
                       </span>
                   </div>
               `
            }).join('')
            document.getElementById(`${match.id}_handap`).innerHTML = handapEl;
        } else {
            document.getElementById(`${match.id}_handap`).innerHTML = ` `;
        }
        if (match.over_under && match.over_under.length > 0) {
            let ouEl = match.over_under?.slice(0, 3).map(h => {
                return `
                <div class="handicap-row">
                    <span>${h.v}</span>
                    <span class="odds-cell">
                        <span class="odds-item" >${h.a}</span>  
                    </span>
                    <span class="odds-cell">
                        <span class="odds-item" >${h.b}</span> 
                    </span>
                </div>
            `
            }).join('')
            document.getElementById(`${match.id}_ou`).innerHTML = ouEl;
        } else {
            document.getElementById(`${match.id}_ou`).innerHTML = ` `;
        }

        if (match.moneyline) {
            let moneylineEl = match.moneyline ? `<div class="handicap-row">
                    <span>${match.moneyline.v}</span>
                    <span class="odds-cell">
                        <span class="odds-item">${match.moneyline.a}</span>
                    </span>
                    <span class="odds-cell">
                        <span class="odds-item">${match.moneyline.b}</span>
                    </span>
                </div>` : ``
            document.getElementById(`${match.id}_moneyline`).innerHTML = moneylineEl;
        } else {
            document.getElementById(`${match.id}_moneyline`).innerHTML = ``;
        }
    }

}


function createMatch(match) {
    const matchEl = document.createElement("div");
    matchEl.className = "match-item";
    matchEl.id = match.id; // 用于后续更新
    let id = match.id
    let handapEl = match.handap?.slice(0, 3).map(h => {
        return `
            <div class="handicap-row">
               <span>${h.v}</span>
               <span class="odds-cell">
                   <span class="odds-item">${h.a}</span>  
               </span>
               <span class="odds-cell">
                   <span class="odds-item">${h.b}</span>  
               </span>
           </div>
       `
    }).join('')
    let ouEl = match.over_under?.slice(0, 3).map(h => {
        return `
        <div class="handicap-row">
            <span>${h.v}</span>
            <span class="odds-cell">
                <span class="odds-item" >${h.a}</span>  
            </span>
            <span class="odds-cell">
                <span class="odds-item"  >${h.b}</span> 
            </span>
        </div>
    `
    }).join('')

    let moneylineEl = match.moneyline ? `<div class="handicap-row">
                        <span>${match.moneyline.v}</span>
                        <span class="odds-cell">
                            <span class="odds-item">${match.moneyline.a}</span>
                        </span>
                        <span class="odds-cell">
                            <span class="odds-item">${match.moneyline.b}</span>
                        </span>
                    </div>` : ``

    matchEl.innerHTML = ` 
            <div class="time-score"> 
                <div class="time" id="${id}_time">${match.time}</div>
                <div class="score" id="${id}_score">${match.score}</div>
            </div> 
            <div class="league" id="${id}_league">${match.league}</div> 
            <div class="teams">
                <div class="team home" id="${id}_home">${match.home}</div>
                <div class="team away" id="${id}_away">${match.away}</div>
            </div> 
            <!-- 让球盘口 -->
            <div>
                <div class="handicap-label">让球</div>
                <div class="handicap-group" id="${id}_handap">
                ${handapEl ? handapEl : ""}  
                </div>
            </div>
            <!-- 大小球盘口 -->
            <div>
                <div class="overunder-label">大小球</div>
                <div class="handicap-group" id="${id}_ou">
                ${ouEl ? ouEl : ""}  
                </div>
            </div> 
            <!-- 上半场让球盘口 -->
            <div>
                <div class="handicap-label">胜平负</div>
                <div class="handicap-group" id="${id}_moneyline">
                     ${moneylineEl}
                </div>
            </div> 
    `;

    return matchEl;
}


function goalTips(obj) {
    let match = localStorage.getItem(obj.id)
    if (match) {
        return
    }
    localStorage.setItem(obj.id, obj)
    showToast(`${obj.home} v ${obj.away} [${obj.time}]`);
}